import { ElMessage, ElMessageBox } from "element-plus";
import { nextTick } from "vue";
import { store, widget, graphicLayer, map } from "@/utils/global";
import { deleteFloader, updateFloaderName, addFloader, updateFloaderLock, deleteFloaderAllData, updateFloaderLockDraw, copyFolder } from "@/api/coverage";
import { removeDrawData, copyDraws, updateDrawData } from "@/api/draw";
import { calcVolume } from "@/utils/draw/saveEditorDrawData";
import renderer from "@/utils/draw/renderer";
/**
 * 右键菜单方法
 */
export const menuFunction = {
    /**
     * 属性编辑
     */
    graphicEditing: () => {
        let id = store.rightClickData.id;
        // nextTick(() => {
        let graphic = graphicLayer.getGraphicById(id);
        if (graphic) {
            graphic.startEditing();
            graphic.flyTo();
            // 单击标绘,选中树菜单
            store.tree.setCurrentKey(graphic.id, true);
            widget.property = true;
            widget.coverage = false;
        } else {
            ElMessage.error("获取标绘数据出错!");
        }

        // });
    },
    /**
     * 删除文件夹
     */
    deleteTreeFloader: () => {
        let node = store.rightClickData;
        ElMessageBox.confirm("此操作将永久删除该文件夹及内容, 是否继续?", "删除文件夹", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            deleteFloader({
                id: node.id,
            }).then((res) => {
                clearFloaderData(node);
                store.tree.remove(node.id);
                ElMessage.success("删除成功");
            });
        });
    },
    /**
     * 重命名文件夹
     */
    renameTreeFloader: () => {
        let node = store.rightClickData;
        ElMessageBox.prompt("请输入新名称", "重命名", {
            inputValue: node.name,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
        }).then(({ value }) => {
            if (value) {
                // console.log(node);
                // return;
                if (node.type == "folder") {
                    updateFloaderName({
                        id: node.id,
                        folderName: value,
                    }).then((res) => {
                        node.name = value;
                        ElMessage.success("修改成功");
                    });
                } else {
                    updateDrawData({
                        id: node.id,
                        name: value,
                    }).then((res) => {
                        node.name = value;
                        ElMessage.success("修改成功");
                    });
                }
            } else {
                ElMessage.error("名称不能为空");
            }
        });
    },
    /**
     * 新建文件夹
     */
    addTreeFloader: () => {
        let node = store.rightClickData;
        ElMessageBox.prompt("请输入文件夹名称", "添加文件夹", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
        }).then(({ value }) => {
            if (value) {
                addFloader({
                    parentFolder: node.id,
                    folderName: value,
                    baseId: store.baseId,
                }).then((res) => {
                    console.log(res);
                    node.children.push(res.data);
                    ElMessage.success("添加成功");
                });
            } else {
                ElMessage.error("名称不能为空");
            }
        });
    },
    /**
     * 锁定文件夹
     */
    lockTreeFloader: () => {
        let node = store.rightClickData;
        console.log(node);

        ElMessageBox.confirm(`此操作将锁定该${node.type == "folder" ? "文件夹" : "标绘"}, 将无法对其进行编辑, 是否继续?`, `锁定${node.type == "folder" ? "文件夹" : "标绘"}`, {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            if (node.type == "folder") {
                // 文件夹
                updateFloaderLock({
                    id: node.id,
                    isLocked: 1,
                }).then((res) => {
                    node.isLocked = 1;
                    locks(node.children, 1);
                    ElMessage.success("操作成功");
                });
            } else {
                // 标绘
                updateFloaderLockDraw({
                    drawId: node.id,
                    isLocked: 1,
                }).then((res) => {
                    node.isLocked = 1;
                    ElMessage.success("操作成功");
                });
            }
        });
    },
    /**
     * 解锁文件夹
     */
    unlockTreeFloader: () => {
        let node = store.rightClickData;
        console.log(node);
        ElMessageBox.confirm(`此操作将解锁该${node.type == "folder" ? "文件夹" : "标绘"}, 将可以对其进行编辑, 是否继续?`, `解锁${node.type == "folder" ? "文件夹" : "标绘"}`, {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            if (node.type == "folder") {
                // 文件夹
                updateFloaderLock({
                    id: node.id,
                    isLocked: 0,
                }).then((res) => {
                    node.isLocked = 0;
                    locks(node.children, 0);
                    ElMessage.success("操作成功");
                });
            } else {
                // 标绘
                updateFloaderLockDraw({
                    drawId: node.id,
                    isLocked: 0,
                }).then((res) => {
                    node.isLocked = 0;
                    ElMessage.success("操作成功");
                });
            }
        });
    },
    /**
     * 删除内容
     */
    deleteTreeFloaderContent: () => {
        let node = store.rightClickData;
        if (node.isLocked == "1") {
            ElMessageBox.alert("请先解锁后再进行操作!");
        } else {
            if (node.children && node.children.length == 0) {
                ElMessage.error("该文件夹内没有内容!");
                return false;
            }
            ElMessageBox.confirm("此操作将删除该文件夹下的所有内容, 是否继续?", "删除内容", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                deleteFloaderAllData({
                    id: node.id,
                }).then((res) => {
                    ElMessage.success("删除成功");
                    clearFloaderData(node);
                });
            });
        }
    },
    /**
     * 删除单个标绘
     */
    removeGraphic: () => {
        let id = store.rightClickData.id;
        if (id == "0000000000") {
            let graphic = graphicLayer.getGraphicById(id);
            graphicLayer.removeGraphic(graphic);
            return false;
        }
        let node = store.tree.getNode(id).data;
        if (node.isLocked == "1") {
            ElMessageBox.alert("请先解锁后再进行操作!");
        } else {
            let tipText = "";
            if (node.type == "xyz") {
                // console.log(node);
                ElMessageBox.confirm(`此操作将删除『 ${node.name} 』, 是否继续?`, "删除标绘", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    removeDrawData({
                        id: node.id,
                    }).then((res) => {
                        ElMessage.success("删除成功");
                        nextTick(() => {
                            map.removeLayer(map.getLayerById(id));
                            store.tree.remove(node);
                        });
                    });
                });
            } else {
                let graphic = graphicLayer.getGraphicById(id);
                if (graphic.options.isCustom) {
                    tipText = `『 ${node.name} 』为自定义标绘原始数据, 此操作将删除该标绘, 是否继续?`;
                } else {
                    tipText = `此操作将删除『 ${node.name} 』, 是否继续?`;
                }
                ElMessageBox.confirm(tipText, "删除标绘", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    removeDrawData({
                        id: node.id,
                    }).then((res) => {
                        ElMessage.success("删除成功");
                        nextTick(() => {
                            graphicLayer.removeGraphic(graphic);
                            store.tree.remove(node);
                        });
                    });
                });
            }
        }
    },
    /**
     * 数据统计
     */
    statistics: () => {
        // 地图数据
        let node: any = store.rightClickData;
        let graphics: any = [];
        statisticFonc(node.children, graphics);
        nextTick(() => {
            if (graphics.length == 0) {
                ElMessage.error("该文件夹下没有标绘数据!");
                return false;
            }
            store.rightClickData = undefined;
            let statistics = widget.statistics;
            statistics.show = true;
            // 数据初始化
            statistics.data.forEach((item: any) => {
                if (item.type == "select") {
                    item.value = "1";
                } else {
                    item.value = 0;
                    item.pluralNum = 0;
                }
            });
            graphics.forEach((v: any, i: any) => {
                // 数据类型
                let type = v.options.plottingType;
                statistics.data.forEach((item: any) => {
                    // 数据汇总,,总数据
                    if (item.type == "total" && item.dataType == "total") {
                        item.value = graphics.length;
                    }
                    if (item.type.includes(type)) {
                        // 数据汇总,总数据
                        if (item.dataType == "total") {
                            item.value += 1;
                        }
                        // 数据汇总,长度
                        if (item.dataType == "length") {
                            item.value += v.distance;
                        }
                        // 数据汇总,面积
                        if (item.dataType == "area") {
                            if (type == "plane") {
                                item.value += v.options.style.dimensions_y * v.options.style.dimensions_x;
                                item.pluralNum += v.options.style.dimensions_y * v.options.style.dimensions_x;
                            } else {
                                item.value += v.area;
                                item.pluralNum += v.area;
                            }
                        }
                        // 数据汇总,体积
                        if (item.dataType == "volume") {
                            item.value += calcVolume(v);
                        }
                    }
                });
            });
        });
        // 标绘数据
        // let graphics = graphicLayer.getGraphics();
        // console.log(store.rightClickData);
    },
    /**
     * 剪切
     */
    cut: () => {
        // 获取右键点击的节点
        let node = store.rightClickData;
        // 复制到剪切板
        store.cutCopyData = JSON.parse(JSON.stringify(node));
        // 删除节点
        store.tree.remove(node);
        if (node.type != "folder") {
            graphicLayer.getGraphicById(node.id).show = false;
        }
        store.handType = 0;
    },
    /**
     * 复制
     */
    copy: () => {
        // 获取右键点击的节点
        let node = store.rightClickData;
        // 复制到剪切板
        store.cutCopyData = JSON.parse(JSON.stringify(node));
        console.log(graphicLayer.getGraphicById(node.id));
        store.handType = 2;
    },
    /**
     * 粘贴
     */
    paste: () => {
        let tree = store.tree;
        // 从剪切板获取数据
        let node = store.cutCopyData;
        console.log(node);
        // 粘贴到当前节点
        let parent = store.rightClickData;
        if (node) {
            if (node.type == "folder") {
                // 文件夹
                copyFolder({
                    folderId: node.id,
                    pid: parent.id,
                    isPaste: store.handType,
                }).then((res: any) => {
                    let data = res.data.baseFolder.newFolder;
                    if (store.handType == 2) {
                        // 创建新的树节点----复制
                        data.forEach((v: any) => {
                            tree.append(newTreeNode(v, "folder"), v.parentFolder);
                            if (v.isShow) {
                                nextTick(() => {
                                    tree.setChecked(v.id, true);
                                });
                            }
                        });
                        if (res.data.baseFolder.newDraw && res.data.baseFolder.newDraw.length > 0) {
                            // 标绘操作
                            let drawData = res.data.baseFolder.newDraw;
                            renderer(drawData);
                            drawData.forEach((v: any) => {
                                tree.append(newTreeNode(v, v.type), v.folderId);
                                if (v.isShow) {
                                    nextTick(() => {
                                        tree.setChecked(v.id, true);
                                    });
                                }
                            });
                        }
                    } else if (store.handType == 0) {
                        // 创建新的树节点----剪切
                        tree.append(node, parent);
                        pasteFonc(node);
                    }
                    ElMessage.success("粘贴成功");
                    // 清空剪切板
                    store.cutCopyData = undefined;
                    // 清空右键点击的节点
                    store.rightClickData = undefined;
                });
            } else {
                // 标绘
                copyDraws({
                    drawId: node.id,
                    folderId: parent.id,
                    isPaste: store.handType,
                }).then((res: any) => {
                    let data = res.data.draw;
                    if (store.handType == 2) {
                        // 复制
                        renderer([data]);
                    } else {
                        // 剪切
                        graphicLayer.getGraphicById(node.id).show = true;
                    }
                    tree.append(newTreeNode(data, data.type), data.folderId);
                    if (data.isShow) {
                        nextTick(() => {
                            tree.setChecked(data.id, true);
                        });
                    }

                    // 清空剪切板
                    store.cutCopyData = undefined;
                    // 清空右键点击的节点
                    store.rightClickData = undefined;
                });
            }
        } else {
            ElMessage.error("剪切板为空!");
        }
    },
    /**
     * 保存文件夹
     */
    saveTreeFloader: () => {
        // 获取右键点击的节点
        let node = store.rightClickData;
        console.log(node);
        ElMessage.warning("该功能暂未开放!");
        // 保存文件夹
        // saveFloader({
        //     id: node.id,
        //     name: node.name,
        // }).then((res) => {
        //     ElMessage.success("保存成功");
        // });
    },
};
/**
 * 锁定-解锁文件夹递归函数
 */
const locks = (data: any, value: Number) => {
    data.forEach((v: any, i: any) => {
        v.isLocked = value;
        if (v.children && v.children.length > 0) {
            locks(v.children, value);
        }
    });
};
/**
 * 清空文件夹标绘
 */
const clearFloaderData = (data: any) => {
    data.children.forEach((v: any) => {
        if (v.type != "folder" && v.pid == data.id) {
            setTimeout(() => {
                console.log(v);
                let graphic = graphicLayer.getGraphicById(v.id);
                graphicLayer.removeGraphic(graphic);
                store.tree.remove(v);
                store.tree.setChecked(data.id, false);
            }, 300);
        } else {
            clearFloaderData(v);
        }
    });
};
/**
 * 统计递归函数
 */
const statisticFonc = (data: any, graphics: any) => {
    data.forEach((v: any) => {
        if (v.type != "folder") {
            graphics.push(graphicLayer.getGraphicById(v.id));
        }
        if (v.children && v.children.length > 0) {
            statisticFonc(v.children, graphics);
        }
    });
};
/**
 * 粘贴---递归函数
 */
const pasteFonc = (data: any) => {
    console.log(data, "data");
    let tree = store.tree;
    // if (data.type == "folder") {
    if (data.show) {
        nextTick(() => {
            tree.setChecked(data.id, true);
        });
    }
    if (data.children && data.children.length > 0) {
        data.children.forEach((v: any) => {
            pasteFonc(v);
        });
    }
    // }
};
/**
 * 粘贴---创建新的树节点
 */
const newTreeNode = (data: any, type: string) => {
    let node = {
        editor: true,
        id: data.id,
        isLocked: data.isLocked ? 1 : 0,
        name: data.folderName ? data.folderName : data.name,
        pid: data.parentFolder ? data.parentFolder : data.folderId,
        show: data.isShow == 1 || data.isShow ? true : false,
        type: type,
        icon: data.icon ? data.icon : "",
    };
    return node;
};
